package edu.cs.usask.ca.silver.plugin.rcp.handlers.create;

import org.apache.log4j.Logger;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.handlers.HandlerUtil;

import edu.cs.usask.ca.silver.businesslogic.ids.ScenarioCollectionID;
import edu.cs.usask.ca.silver.plugin.rcp.Activator;
import edu.cs.usask.ca.silver.plugin.rcp.dialogs.create.CreateScenarioDialog;
import edu.cs.usask.ca.silver.plugin.rcp.handlers.create.helper.CreateDataProcedures;
import edu.cs.usask.ca.silver.plugin.rcp.jobs.LoggerReportScheduler;
import edu.cs.usask.ca.silver.plugin.rcp.views.projectviewer.ProjectViewI;

/**
 * TODO documentation
 * 
 * @author Yudi Xue
 * 
 */
public class CreateScenarioHandler extends AbstractHandler {
	private static Logger logger = Logger.getLogger(CreateScenarioHandler.class);

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		ProjectViewI view = (ProjectViewI) HandlerUtil
				.getActiveWorkbenchWindow(event).getActivePage()
				.findView(event.getParameter("projectviewid"));
		ScenarioCollectionID selectedScenarioCollectionID = (ScenarioCollectionID) view
				.getTreeSelectionAsSilverTreeObject().getSilverObjectId();
		try {
			CreateScenarioDialog dialog = new CreateScenarioDialog(Activator
					.getDefault().getWorkbench().getActiveWorkbenchWindow()
					.getShell(), selectedScenarioCollectionID,
					view.getAssociatedStorage());
			dialog.create();
			if (dialog.open() == Window.OK) {
				CreateDataProcedures
						.createNewScenarioFromCreateScenarioDialogWithAScenarioCollectionIdSelected(
								dialog, view.getAssociatedStorage());
				view.updateTree();
			}

		} catch (Exception e) {
			LoggerReportScheduler.scheduleErrorLogging(logger,"error while creating scenario in rcp command handler", e);
		}
		return null;
	}

}
